document.getElementById('memo-form').addEventListener('submit', (e) => {
    e.preventDefault();
    const memoText = document.getElementById('memo-text').value;

    if (memoText) {
        const memo = {
            text: memoText,
            date: new Date().toLocaleString()
        };

        chrome.storage.sync.get(['memos'], (result) => {
            const memos = result.memos || [];
            memos.push(memo);
            chrome.storage.sync.set({ memos }, () => {
                addMemoToList(memo);
                document.getElementById('memo-text').value = '';
            });
        });
    }
});

function addMemoToList(memo) {
    const list = document.getElementById('memo-list');
    const item = document.createElement('li');
    item.textContent = `${memo.date} - ${memo.text}`;

    // 双击事件监听器
    item.addEventListener('dblclick', () => {
        navigator.clipboard.writeText(memo.text).then(() => {
            createNotification('备忘录已复制到剪贴板');
        });
    });


    const deleteButton = document.createElement('button');
    deleteButton.textContent = '删除';
    deleteButton.addEventListener('click', () => {
        deleteMemo(memo);
    });

    item.appendChild(deleteButton);
    list.appendChild(item);
}

function deleteMemo(memo) {
    chrome.storage.sync.get(['memos'], (result) => {
        const memos = result.memos || [];
        const updatedMemos = memos.filter(item => item.text !== memo.text);
        chrome.storage.sync.set({ memos: updatedMemos }, () => {
            const list = document.getElementById('memo-list');
            list.innerHTML = '';
            updatedMemos.reverse().forEach(item => addMemoToList(item));
        });
    });
}

function createNotification(message) {
    const notificationId = `notification-${Date.now()}`;
    chrome.notifications.create(notificationId, {
        type: 'basic',
        iconUrl: 'icons/icon48.png',
        title: '备忘录插件',
        message: message,
        priority: 2
    });

    // 1分钟后自动清除通知
    setTimeout(() => {
        chrome.notifications.clear(notificationId);
    }, 60000);
}

chrome.storage.sync.get(['memos'], (result) => {
    const memos = result.memos || [];
    memos.reverse().forEach(memo => addMemoToList(memo));
});